package com.hxalex.simulationhandle.accessbilityService.manger;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import com.hxalex.simulationhandle.R;
import com.hxalex.simulationhandle.accessbilityService.base.WifiConnect;
import com.hxalex.simulationhandle.accessbilityService.command.base.BaseCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.CheckWifiInMainCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.ConnectWifiCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.SearchWifiCommand;
import com.hxalex.simulationhandle.accessbilityService.model.WifiInfoBean;
import com.hxalex.simulationhandle.accessbilityService.receiver.wifi.CheckWifiInMainReceiver;
import com.hxalex.simulationhandle.accessbilityService.receiver.wifi.ConnectWifiReceiver;
import com.hxalex.simulationhandle.accessbilityService.receiver.wifi.SearchWifiReceiver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by hx_Alex on 2018/5/26.
 */

public class WifiManger implements WifiConnect {
    public static final String ACTIVATION_ACTIVITY_TO_WIFI="ACTIVATION_ACTIVITY_TO_WIFI";
    private static final String TAG = "WifiManger";
    private static Context context;
    private static WifiManger wifiManger;
    private ArrayList<WifiInfoBean> wifiInfoBeanArrayList;//检索到的wifi信息列表
    private ArrayList<WifiInfoBean> connectedWifiList;//已经尝试连接或者已经连接过的wifi列表
    private List<AccessibilityNodeInfo> tabList = null;//wifi万能助手底部按钮列表
    public boolean isSearchWifi = true;//是否检索wifi->当前wifi信息检索完成后置为true完成一次wifi检索
    private AccessibilityNodeInfo wifiAppRootInfo;
    public String nowWifiName="";//当前连接的wifi名
    public static boolean isOpenWifiAppActiviy=false;
    private WifiManger(Context context) {
        this.context = context;
        wifiInfoBeanArrayList = new ArrayList<>();
        connectedWifiList=new ArrayList<>();
        EventBus.getDefault().register(this);
    }


    public static Context getContext() {
        return context;
    }


    public synchronized static WifiManger getWifiManger(Context context) {
        WifiManger.context = context;
        if (wifiManger == null) wifiManger = new WifiManger(context);
        return wifiManger;
    }

    public AccessibilityNodeInfo getWifiAppRootInfo() {
        return wifiAppRootInfo;
    }

    public void setWifiAppRootInfo(AccessibilityNodeInfo wifiAppRootInfo) {
        this.wifiAppRootInfo = wifiAppRootInfo;
    }

    public ArrayList<WifiInfoBean> getWifiInfoBeanArrayList() {
        return wifiInfoBeanArrayList;
    }
    public ArrayList<WifiInfoBean> getConnectedWifiList() {
        return connectedWifiList;
    }
    
    public void setWifiInfoBeanArrayList(ArrayList<WifiInfoBean> wifiInfoBeanArrayList) {
        this.wifiInfoBeanArrayList = wifiInfoBeanArrayList;
 
    }

    @Override
    public void openWifiHelper() {
        Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getResources().getString(R.string.wifi_app_package_name));
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }


    @Override
    public void searchAvailableWifi(AccessibilityNodeInfo info) {
        searchWifiList(info);
        if (wifiInfoBeanArrayList != null && wifiInfoBeanArrayList.size() > 0) 
        {
            isSearchWifi = false;
        }else
        {
            Log.i(TAG,"当前无可用WIFI信息重新检索");
            isSearchWifi=true;
        }
    }

    @Override
    public void connectWifi() {

    }

    @Override
    public void checkWifiConnect() {

    }


    public Boolean[] isOpenWifiApp = new Boolean[]{false, false};

    /***
     * 检查是否已经打开WiFi万能钥匙主页
     * @param s
     */
    public boolean checkIsOpenWifiApp(String s) {

        String text = s;
        if (text.contains("朋友")) {
            isOpenWifiApp[0] = true;
        } else if (text.equals("连接")) {
            isOpenWifiApp[1] = true;
        }

        if (isOpenWifiApp[0] && isOpenWifiApp[1]) {
            Log.i(TAG, "已进入Wifi钥匙助手主页");
            return true;
        }
        return false;
    }




    public int searchAvailableWifiCount(String canConnectNum) {
        //判断是否已经进入wifi助手
        //关键词->发现n个安全免费热点
//        if(canConnectNum.contains("成功连接")) return 1;
        int num = 0;
        int startIndex = canConnectNum.indexOf("现");
        int endIndex = canConnectNum.indexOf("个");
        if (startIndex != -1 && endIndex != -1) {
            num = Integer.valueOf(canConnectNum.substring(startIndex + 1, endIndex));
            Log.i(TAG, "搜索到: " + num + " 个热点");
            return num;
        } else {
            Log.i(TAG, "没有热点可以使用");
            return -1;
        }
    }



    /***
     * 搜索wifi万能助手底部按钮
     */
    public void searchWifiTab(AccessibilityNodeInfo info) {
        List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = info.findAccessibilityNodeInfosByViewId("com.snda.wifilocating:id/tab_container");
        if (accessibilityNodeInfosByViewId != null && accessibilityNodeInfosByViewId.size() > 0) {
            tabList = accessibilityNodeInfosByViewId;
        }
    }

    /***
     * 搜索wifi万能助手搜索到的当前所有wifi
     */
    public synchronized void searchWifiList(AccessibilityNodeInfo info) {
        if (info == null) return;
        List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = info.findAccessibilityNodeInfosByViewId("com.snda.wifilocating:id/list");
        if (accessibilityNodeInfosByViewId != null && accessibilityNodeInfosByViewId.size() > 0) {
            recycle(info);
        }
        //移除已连接或以尝试连接失败的wifi
        for(WifiInfoBean b:connectedWifiList)
        {
            for(int i=0;i<wifiInfoBeanArrayList.size();i++)
            {
                if(b.getWifiName().equals(wifiInfoBeanArrayList.get(i).getWifiName()))
                {
                    wifiInfoBeanArrayList.remove(i);
                }
            }
        }
        
        for (WifiInfoBean bean : wifiInfoBeanArrayList) {
            Log.i(TAG, bean.toString());
        }
    }


    public void recycle(AccessibilityNodeInfo info) {

        if (info.getClassName().equals("android.widget.LinearLayout") && info.getViewIdResourceName() == null) {
            //wifi名称
            List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = info.findAccessibilityNodeInfosByViewId("com.snda.wifilocating:id/title");
            if (accessibilityNodeInfosByViewId != null && accessibilityNodeInfosByViewId.size() == 1) {
                String wifiName = accessibilityNodeInfosByViewId.get(0).getText() != null ? accessibilityNodeInfosByViewId.get(0).getText().toString() : "";
                for(int i=0;i<wifiInfoBeanArrayList.size();i++)
                {
                    WifiInfoBean bean = wifiInfoBeanArrayList.get(i);
                    if(bean.equals(wifiName))
                    {
                        wifiInfoBeanArrayList.remove(bean);
                    }
                }
                wifiInfoBeanArrayList.add(new WifiInfoBean(info, wifiName));
            }
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(info.getChild(i));
                }
            }
        }
    }

    public List<AccessibilityNodeInfo> getTabList() {
        return tabList;
    }

    public boolean isWifi() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }


    /***
     * wifi连接后的回调
     * 事件来源@{@link com.hxalex.simulationhandle.accessbilityService.receiver.wifi.service.WifiInfoService}
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getWifiUsabilityInfo(Integer msg)
    {

        WifiManager wifiManager = (WifiManager)context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID().replace("\"","");

        if(ssid==null)
        {
            loadAllWifiCommand();
            return;
        }
        // 0->wifi可用 1->需要网络验证  2->wifi不可用
        if(msg==0)
        {
            //当前wifi没有更改
            if(ssid.equals(nowWifiName))
            {
                Log.i(TAG," wifi没有更改重新检索.........");
                //测试下一个连接动作
                Log.i(TAG," 测试下一个连接动作");
                EventBus.getDefault().post(SearchManger.OPEN_WAKE_WINWODS);
                CommandManger.getManger().getCommandQueue().clear();
                loadAllWifiCommand();
            }else
            {
                Log.i(TAG," 跳转至模拟搜索逻辑.................`");
                Log.i(TAG," wifi已连接并且可以使用 wifiName:"+ssid);
                nowWifiName=ssid;
                SearchManger searchManger=SearchManger.getSearchManger(context);
                //开始执行检索任务
                CommandManger.getManger().getCommandQueue().clear();
                searchManger.openBrowser();
                CommandManger.getManger().loadBrowserCommandAgain(context,true);
                CommandManger.getManger().loadBrowserCommand(context,true);
            }
        }else 
        {
            Log.e(TAG," wifi无网络连接 wifiName:"+ssid);
            //测试下一个连接动作
            Log.i(TAG," 测试下一个连接动作");
            CommandManger.getManger().getCommandQueue().clear();
            loadAllWifiCommand();
            EventBus.getDefault().post(SearchManger.OPEN_WAKE_WINWODS);
    
        }
    }
    
    
    public void loadAllWifiCommand()
    {
        CommandManger commandManger=CommandManger.getManger();
        ArrayBlockingQueue<BaseCommand> commandQueue = commandManger.getCommandQueue();
        commandQueue.offer(new CheckWifiInMainCommand(wifiManger, new CheckWifiInMainReceiver(wifiManger)));
        commandQueue.offer(new SearchWifiCommand(wifiManger, new SearchWifiReceiver(wifiManger)));
        commandQueue.offer(new ConnectWifiCommand(wifiManger, new ConnectWifiReceiver(wifiManger)));
    }
    
    public static void ClearManger()
    {
        wifiManger=null;
    }


}
